﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using AnnouncementManager.Schemas;

namespace AnnouncementManager
{
    public class AnnouncementRepository
    {
        private static object _locker = new object();
        private string _pathToAnnouncements;
        private string _announcementsCacheKey;
        private const double CacheTimeoutMinutes = 5;

        public AnnouncementRepository()
        {
            var path = ConfigurationManager.AppSettings["PathToAnnouncements"];
            _pathToAnnouncements = HttpContext.Current.Server.MapPath(path);
        }

        public List<Announcement> GetAllAnnouncements()
        {
            List<Announcement> result;

            lock (_locker)
            {
                _announcementsCacheKey = "AnnouncementsCache";
                var data = HttpContext.Current.Cache[_announcementsCacheKey] as List<Announcement>;

                if (data == null)
                {
                    data = LoadAllAnnouncements();

                    HttpContext.Current.Cache.Insert(_announcementsCacheKey, data, null, DateTime.Now.AddMinutes(CacheTimeoutMinutes), TimeSpan.Zero);
                }

                result = data;
            }

            return result;
        }

        private List<Announcement> LoadAllAnnouncements()
        {
            var list = new List<Announcement>();
            var items = Directory.GetFiles(_pathToAnnouncements, "*.xml");

            foreach (var item in items)
            {
                var announcement = XmlSerializationHelper.XmlDeserialize<announcement>(File.ReadAllText(item));
                list.Add(new Announcement { Id = announcement.id, Title = announcement.title, Time = announcement.date, FullBody = HttpUtility.HtmlDecode(announcement.fullBody) });
            }

            return list;
        }

        public void AddAnnouncement(Announcement announcement)
        {
            var data = XmlSerializationHelper.XmlSerialize(announcement);
            var name = Path.Combine(_pathToAnnouncements, DateTime.Now.ToString("yyyy-MM-dd__HH-mm-ss", CultureInfo.InvariantCulture)) + ".xml";

            File.WriteAllText(name, data);
        }
    }
}
